package com.zf.shuashua.ui.dialog;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.aliyun.svideo.common.utils.NetUtils;
import com.lxj.xpopup.util.KeyboardUtils;
import com.meis.base.mei.base.BaseDialog;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.R;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.comment.CommentEntity;
import com.zf.shuashua.bean.comment.VideoCommentEntity;
import com.zf.shuashua.utils.ToastUtil;

public class BottomCommentDialog extends BaseDialog {

    EditText mEtHint;
    TextView mTvPublish;

    // 评论列表所在索引
    private int position = 0;
    private String videoOrCommentId = "";
    private String atName = "";
    // @ 谁
    private boolean isAt;

    // 回复二级回复
    private boolean isLevel2Reply;

    private String toUserId;

    private OnPublishListener mListener;

    public BottomCommentDialog setParams(String videoId, int position) {
        this.position = position;
        this.videoOrCommentId = videoId;
        return this;
    }

    public BottomCommentDialog(String videoOrCommentId, String toUserId, int position, String atName, boolean isAt, boolean isLevel2Reply, OnPublishListener listener) {
        this.position = position;
        this.videoOrCommentId = videoOrCommentId;
        this.mListener = listener;
        this.atName = atName;
        this.isAt = isAt;
        this.isLevel2Reply = isLevel2Reply;
        this.toUserId = toUserId;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_bottom_comment;
    }

    @Override
    protected void initView() {
        mEtHint = findViewById(R.id.et_hint);
        mTvPublish = findViewById(R.id.tv_send);
        mEtHint.post(() -> {
            mEtHint.requestFocus();
            KeyboardUtils.showSoftInput(mEtHint);
        });

        if (isAt) {
            mEtHint.setHint("回复 " + "@" + atName + "：");
        }

        mEtHint.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                InputMethodManager manager = ((InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE));
                if (manager != null)
                    manager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        });
    }

    @Override
    protected void initData() {
        mEtHint.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mTvPublish.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
            }
        });

        mTvPublish.setOnClickListener(v -> {
            if (!NetUtils.isNetworkConnected(getContext())) {
                Toast.makeText(getContext(), "请检查网络连接", Toast.LENGTH_SHORT).show();
                return;
            }
            mTvPublish.setEnabled(false);
            requestPublishComment();
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    // 请求发表评论
    private void requestPublishComment() {
        String content = mEtHint.getText().toString().trim();

        if (isAt) {
            // 回复评论
            HttpData.getInstance().replyLevel2Comment(videoOrCommentId, toUserId, content, new ACallback<BaseData<VideoCommentEntity>>() {
                @Override
                public void onSuccess(BaseData<VideoCommentEntity> data) {
                    if (data.getCode() == 200) {
                        if (mListener != null && data.getData() != null && data.getData().comment != null && data.getData().reply != null) {
                            // 获取一级评论ID

                            data.getData().reply.parentIdHelper = data.getData().comment.id;
                            mListener.onPublish(position, true, isLevel2Reply, data.getData().reply);
                        }
                        ToastUtil.show(getContext(), "回复成功");
                    } else {
                        ToastUtil.show(getContext(), data.getMessage());
                    }
                    mTvPublish.setEnabled(true);

                    KeyboardUtils.hideSoftInput(mEtHint);
                    dismiss();
                }

                @Override
                public void onFail(int errCode, String errMsg) {
                    mTvPublish.setEnabled(true);
                }
            });
            return;
        }

        // 回复视频
        HttpData.getInstance().replyComment(videoOrCommentId, content, new ACallback<BaseData<VideoCommentEntity>>() {
            @Override
            public void onSuccess(BaseData<VideoCommentEntity> data) {
                if (data.getCode() == 200) {
                    if (mListener != null && data.getData() != null) {
                        mListener.onPublish(position, false, isLevel2Reply, data.getData().comment);
                    }
                    ToastUtil.show(getContext(), "评论成功");
                } else {
                    ToastUtil.show(getContext(), data.getMessage());
                }

                mTvPublish.setEnabled(true);
                KeyboardUtils.hideSoftInput(mEtHint);
                dismiss();
            }

            @Override
            public void onFail(int errCode, String errMsg) {
                mTvPublish.setEnabled(true);
            }
        });

    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        if (mListener != null) {
            mListener.onCloseKeyboard();
        }
        super.onDismiss(dialog);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onStart() {
        super.onStart();

        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        // 显示在底部
        params.gravity = Gravity.BOTTOM;
        // 宽度填充满屏
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        //显示dialog的时候,就显示软键盘
        params.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE;
        window.setAttributes(params);

        // 这里用透明颜色替换掉系统自带背景
        int color = ContextCompat.getColor(getActivity(), android.R.color.transparent);
        window.setBackgroundDrawable(new ColorDrawable(color));
    }

    public interface OnPublishListener {
        void onPublish(int position, boolean isAt, boolean isLevel2Reply, CommentEntity entity);

        void onCloseKeyboard();
    }

    public BottomCommentDialog setOnPublishListener(OnPublishListener listener) {
        this.mListener = listener;
        return this;
    }
}
